//
//  HTInterstitialAd.swift
//  MagaCore
//
//  Created by MrMessy on 2023/5/19.
//

import Foundation
import SwiftUI
import AppLovinSDK

struct HTInterstitialAd: UIViewControllerRepresentable {
  var var_didLoad: ((MAInterstitialAd) -> Void)?
  var var_didHide: (() -> Void)?

  func makeUIViewController(context: Context) -> HTInterstitialAdViewController {
    let viewController = HTInterstitialAdViewController()
    viewController.var_didLoad = var_didLoad
    viewController.var_didHide = var_didHide
    return viewController
  }

  func updateUIViewController(_ uiViewController: HTInterstitialAdViewController, context: Context) {
    // No need to update the view controller
  }
}

class HTInterstitialAdViewController: UIViewController, MAAdDelegate {
    // 广告单元对应的对象
  var var_interstitialAd: MAInterstitialAd!
    // 重试次数
  var var_retryAttempt = 0.0
    // 加载广告回调
  var var_didLoad: ((MAInterstitialAd) -> Void)?
    // 隐藏回调点击
  var var_didHide: (() -> Void)?

  override func viewDidLoad() {
    super.viewDidLoad()
    ht_createInterstitialAd()
  }

  func ht_createInterstitialAd() {
      // 初始化广告单元
    var_interstitialAd = MAInterstitialAd(adUnitIdentifier: HTConfig.STATIC_interstitialId)
      // 设置代理
    var_interstitialAd.delegate = self

    // 加载第一个广告
    var_interstitialAd.load()
  }

  // MARK: MAAdDelegate Protocol

  func didLoad(_ ad: MAAd) {
    // 广告已准备好播放。“AtlantialAd.isReady”现在将返回“true”

    // 重置次数清0
    var_retryAttempt = 0
//    interstitialAd.show()
      // 返回给外成调用
    var_didLoad!(var_interstitialAd)
  }

  func didFailToLoadAd(forAdUnitIdentifier adUnitIdentifier: String, withError error: MAError) {
    // Interstitial ad failed to load
    // We recommend retrying with exponentially higher delays up to a maximum delay (in this case 64 seconds)

    var_retryAttempt += 1
      // 计算2的次方，计算 6.0 和 var_retryAttempt 的最小值。这样可以确保幂的指数不会超过 6.0，即最大等待时间是 2^6 = 64 秒，进行重新请求
    let delaySec = pow(2.0, min(6.0, var_retryAttempt))

    DispatchQueue.main.asyncAfter(deadline: .now() + delaySec) {
      self.var_interstitialAd.load()
    }
  }

  func didDisplay(_ ad: MAAd) {}

  func didClick(_ ad: MAAd) {}

  func didHide(_ ad: MAAd) {
    // Interstitial ad is hidden. Pre-load the next ad
//    interstitialAd.load()
    var_didHide!();
  }

  func didFail(toDisplay ad: MAAd, withError error: MAError) {
    // Interstitial ad failed to display. We recommend loading the next ad
    var_interstitialAd.load()
  }
}
